package com.athena.dal.dao;

import java.io.Serializable;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;

import com.athena.dal.compositeEntities.FacultyRoutines;
import com.athena.dal.entities.Faculty;
import com.athena.dal.entities.User;

public class FacultyDaoImpl implements FacultyDao{

	@Autowired
	private GenericDao genericDao;

	public List<FacultyRoutines> getMyRoutines(User user, long start, long end){	 

		List<FacultyRoutines> routines = new ArrayList<FacultyRoutines>();
		if(user != null && genericDao != null){
			Faculty faculty = (Faculty) user;
			EntityManager entityManager = genericDao.getEntityManager();
			if(entityManager != null) {
				// set current date to 1st Jan 2013
				long MILLIS_IN_A_DAY = 86400000;
					
				Calendar cal = Calendar.getInstance();
				cal.set(2013, 0, 1, 0, 0, 0);
				
			
				String queryString = "Select subject.name,subject.code, cl.id," + 
						"cl.section, learningPlace.building,learningPlace.name, " +						
						"routineInstance.startTime, routineInstance.endTime," +
						"routineInstance.yearOfDay FROM RoutineInstance routineInstance, " +
						" Teach teach, Subject subject, Class cl, " +
						"LearningPlace learningPlace where (" +
						"teach.subject.id = subject.id " + 
						"AND subject.classId = cl.id " +
						"AND cl.id = routineInstance.clazz.id " +
						"AND routineInstance.learningPlace.id = learningPlace.id " +
						"AND routineInstance.subject.id = subject.id " +
						"AND " + start + "<= " + end +" " +
						"AND routineInstance.faculty.id = '"+ faculty.getId() +"' " +
						"AND routineInstance.yearOfDay >= " + (start + MILLIS_IN_A_DAY - cal.getTimeInMillis())/MILLIS_IN_A_DAY + " " + 
						"AND routineInstance.yearOfDay <= " + (end + MILLIS_IN_A_DAY - cal.getTimeInMillis())/MILLIS_IN_A_DAY + " " +
						"AND teach.faculty.id = '"+ faculty.getId() + "') ";
				Query query = entityManager.createQuery(queryString);
				Iterator results = query.getResultList().iterator();
				while(results.hasNext()) {
					Object [] row = (Object[]) results.next();
					routines.add(new FacultyRoutines((String)row[0], (String)row[1],
							(Integer)row[2],(String)row[3],(String)row[4],
							(String)row[5], (Time)row[6],(Time) row[7], (Long)row[8]));
				}
				System.out.println("routine size is " + routines.size());
			}else {
				System.err.println(getClass().getName() + " :: Entity Manager is NULL");
			}
		} else {
			System.out.println("**************** Generic Dao is null");
		}
		return routines;
	}
	
	public <T> T findById(Class<T> entityClass, final Serializable ID){
		if(genericDao != null){
				return genericDao.findById(entityClass, ID);			
		}
		return null;
	}
}